<template>
  <base-load-page :loadState="false" class="base-load-page">
    <template #head>
      <div style="padding-bottom: 15px" class="head-box">
        <div class="left-box">
          <base-input-search
            v-model="filterData.referralLinkId"
            clearable
            placeholder="请输入推广链接id"
            style="width: 230px"
            :prefixIcon="IconSearch"
            @blur="referralLinkIdLimit"
            @input="referralLinkIdLimit"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <base-input-search
            v-model="filterData.createName"
            clearable
            placeholder="请输入投放人"
            style="width: 230px"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <base-input-search
            v-model="filterData.dramaTitle"
            clearable
            placeholder="请输入短剧名"
            style="width: 230px"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <base-date-picker
            v-model="dataRange"
            valueFormat="YYYY-MM-DD"
            format="YYYY-MM-DD"
            type="datetimerange"
            startPlaceholder="开始日期"
            endPlaceholder="结束日期"
            style="flex-grow: 0; width: 350px"
            clearable
            @change="getAxiosData(true)"
          ></base-date-picker>
        </div>

      </div>
    </template>
    <div class="page-content">
      <div class="statistics-block">
        <div v-for="i in statisticsData" :key="i.flag" class="statistics">
          <div class="title">{{ i.name }}</div>
          <div class="value" :class="{ 'operable': i.type === 'primary' }">{{ i.format(censusData) }}</div>
        </div>
      </div>
      <el-table ref="elTableRef" v-loading="baseData.loading" border height="100%" :data="tableData" showOverflowTooltip stripe style="width: 100%">
        <template #empty>
          <base-empty :description="description" :pageLoadButton="[{ text: '重新加载', callBack: () => getAxiosData() }]"></base-empty>
        </template>
        <el-table-column
          fixed
          type="index"
          :index="(index: number) => (filterData.current - 1) * filterData.size + index + 1"
          label="编号"
          sortable
          width="60"
          align="center"
          headerAlign="center"
        ></el-table-column>
        <el-table-column label="创建时间" prop="thatdayDate" minWidth="120"></el-table-column>
        <el-table-column label="投放人" minWidth="100" prop="createName"></el-table-column>
        <el-table-column label="剧集" minWidth="220">
          <template #default="{ row }">
            <div class="content-wrap">
              <p>
                剧集名称:
                <span>{{ row.dramaTitle }}</span>
              </p>
              <p>
                剧集ID:
                <span>{{ row.dramaId || '-' }}</span>
              </p>
              <el-button link type="warning" size="small" @click="dramaDetails(row.dramaId)">更多信息</el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="投放信息" minWidth="220">
          <template #default="{ row }">
            <div class="content-wrap">
              <p>
                推广链接ID:
                <span class="highlighted">{{ row.referralLinkId }}</span>
              </p>
              <p>
                投放平台:
                <span>{{ row.appName || '-' }}</span>
              </p>
              <el-button v-if="row.referralLinkId" link type="warning" size="small" :loading="row.getReferralLinkLoading" @click="referralLinkDetails(row)">
                更多信息
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="当日" minWidth="220">
          <template #default="{ row }">
            <div class="content-wrap">
              <!--
                <p>
                当日消耗:
                <span>{{ row.cost }}</span>
                </p> 
              -->
              <p>
                今日总收入:
                <span>{{ row.thatdayTotalAmount || '-' }}</span>
              </p>
              <p>
                付款人数:
                <span>{{ row.thatdayPaidUseNum }}</span>
              </p>
              <p>
                总支付笔数:
                <span>{{ row.thatdayPaidTotalNum || '-' }}</span>
              </p>
            </div>
          </template>
        </el-table-column>
        <!--      <el-table-column label="ROI" minWidth="220"> -->
        <!--        <template #default="{ row }"> -->
        <!--          <div class="content-wrap"> -->
        <!--            <p> -->
        <!--              今日ROI: -->
        <!--              <span>{{ convertToPercentage(row.thatdayTotalAmount, row.cost) }}</span> -->
        <!--            </p> -->
        <!--            <p> -->
        <!--              首日ROI: -->
        <!--              <span>{{ row.firstRoi }}%</span> -->
        <!--            </p> -->
        <!--          </div> -->
        <!--        </template> -->
        <!--      </el-table-column> -->
        <el-table-column label="复购" minWidth="220">
          <template #default="{ row }">
            <div class="content-wrap">
              <p>
                复购率:
                <span>{{ convertToPercentage(row.repeatRechargeUserNum, row.thatdayPaidUseNum) }}</span>
              </p>
              <p>
                客单价:
                <span>{{ customRound(divideNumbers(row.thatdayTotalAmount, row.thatdayPaidUseNum)) }}</span>
              </p>
              <!--            <p> -->
              <!--              复购成本: -->
              <!--              <span>{{ convertToPercentage(row.cost, row.repeatRechargeUserNum) }}</span> -->
              <!--            </p> -->
            </div>
          </template>
        </el-table-column>
        <!--      <el-table-column label="新用户" minWidth="220"> -->
        <!--        <template #default="{ row }"> -->
        <!--          <div class="content-wrap"> -->
        <!--            <p> -->
        <!--              点击成本: -->
        <!--              <span>{{ customRound(divideNumbers(row.cost, row.thatdayNewUserNum)) }}</span> -->
        <!--            </p> -->
        <!--            <p> -->
        <!--              付费成本: -->
        <!--              <span>{{ customRound(divideNumbers(row.cost, row.thatdayPaidTotalNum)) }}</span> -->
        <!--            </p> -->
        <!--            <p> -->
        <!--              付费率: -->
        <!--              <span>{{ convertToPercentage(row.thatdayNewUserPayOrderNum, row.active) }}</span> -->
        <!--            </p> -->
        <!--          </div> -->
        <!--        </template> -->
        <!--      </el-table-column> -->
        <el-table-column label="当前新用户" minWidth="220">
          <template #default="{ row }">
            <div class="content-wrap">
              <p>
                新用户数量:
                <span>{{ row.thatdayNewUserNum }}</span>
              </p>
              <p>
                新用户收入:
                <span>{{ row.thatdayNewUserAmount }}</span>
              </p>
              <p>
                新用户支付人数:
                <span>{{ row.thatdayNewUserPayNum }}</span>
              </p>
              <p>
                新用户支付笔数:
                <span>{{ row.thatdayNewUserPayOrderNum }}</span>
              </p>
            </div>
          </template>
        </el-table-column>
        <!--
          <el-table-column label="巨量数据" minWidth="220">
          <template #default="{ row }">
          <div class="content-wrap">
          <p>
          点击:
          <span>{{ row.click }}</span>
          </p>
          <p>
          转化:
          <span class="highlighted">{{ row.converts }}</span>
          </p>
          <p>
          展示:
          <span>{{ row.show }}</span>
          </p>
          </div>
          </template>
          </el-table-column> 
        -->
        <el-table-column label="回传数据" minWidth="220">
          <template #default="{ row }">
            <div class="content-wrap">
              <p>
                支付回传笔数:
                <span>{{ row.backNum }}</span>
              </p>
              <p>
                支付回传人数:
                <span>{{ row.backUserNum }}</span>
              </p>
              <el-button link type="warning" size="small" @click="handlerBackRecord(row)">回传记录</el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" minWidth="110"></el-table-column>
        <!--
          <el-table-column sortable fixed="right" label="操作" width="100" align="center" headerAlign="center">
          <template #default="{ row }">
          <div style="display: flex; flex-direction: column; justify-content: space-around; height: 80px; overflow: hidden">
              
          <el-button
          link
          type="primary"
          size="small"
          style="margin-left: 0"
          :loading="row.manualUpdateLoading"
          :icon="SolarInfinityBroken"
          @click="handleManualUpdate(row)"
          >
          手动更新
          </el-button> 
            
          <el-button link type="primary" size="small" style="margin-left: 0" :icon="EpDataLine" @click="handleDayConsume(row)">每日消耗</el-button>
          </div>
          </template>
          </el-table-column> 
        -->
      </el-table>
    </div>
    <template #foot>
      <div class="pagination-box">
        <el-pagination
          v-model:currentPage="filterData.current"
          v-model:pageSize="filterData.size"
          :pageSizes="[20, 30, 40, 50]"
          :disabled="baseData.loading"
          :pagerCount="13"
          layout="total, prev, pager, next, sizes, jumper"
          :total="baseData.total"
          @change="getAxiosData(true)"
        ></el-pagination>
      </div>
    </template>
    <add-promotion-link ref="addPromotionLinkRef"></add-promotion-link>
    <back-record ref="backRecordRef"></back-record>
  </base-load-page>
</template>

<script setup lang="ts">
  import IconSearch from '~icons/ep/search';
  // import EpDataLine from '~icons/ep/data-line';
  // import SolarInfinityBroken from '~icons/solar/infinity-broken';
  import {
    type MonitorLinkReportRequset,
    type MonitorLinkReportResponse,
    getMonitorLinkReportList,
    getReferralCensusData,
    getReferralRecordListAxios,
  } from '@/api/marketing-management';
  import { verifyNumbInput } from '@/utils/verify-number';
  import AddPromotionLink from '@/views/app-main/marketing-management/promotion-link-list/components/add-promotion-link.vue';
  import { convertToPercentage, customRound, divideNumbers, formatNumberWithMoney } from '@/utils/numb';
  import BackRecord from './components/back-record.vue';

  const { proxy } = getCurrentInstance() as any;

  const addPromotionLinkRef = ref<InstanceType<typeof AddPromotionLink>>();
  const backRecordRef = ref<InstanceType<typeof BackRecord>>();
  const elTableRef: $RefComp<'ElTable'> = ref(null);
  const baseData = shallowReactive({
    type: 'add' as 'add' | 'edit',
    /** 加载状态 */
    loading: true,
    /** 总数量 */
    total: 0,
  });

  const router = useRouter();
  const route = useRoute();
  const dataRange = ref<[string, string] | undefined>();
  const filterData = ref<MonitorLinkReportRequset>({
    current: 1,
    size: 40,
    startDate: '',
    endDate: '',
    referralLinkId: '',
    thirdAdvertiserId: '',
    dramaTitle: '',
    createName: '',
  });

  type _MonitorLinkReportResponse = MonitorLinkReportResponse & {
    getReferralLinkLoading?: boolean;
    manualUpdateLoading?: boolean;
  };

  const tableData: Ref<_MonitorLinkReportResponse[]> = ref([]);
  const description = ref('');
  console.log('===========data');
  onMounted(() => {
    dataRange.value = [proxy.$dayjs().format('YYYY-MM-DD'), proxy.$dayjs().format('YYYY-MM-DD')];
    filterData.value.referralLinkId = (route.query.referralLinkId as string) ?? '';
    filterData.value.createName = (route.query.createName as string) ?? '';
    filterData.value.dramaTitle = (route.query.dramaTitle as string) ?? '';

    getAxiosData();
  });

  /** 统计数据 */
  const censusData = ref<Record<string, number>>({
    priceAll: 0,
    orderNum: 0,
  });

  interface StatisticsItem {
    name: string;
    flag: 'thatdayTotalAmount';
    type?: string;
    format: (val: Record<'thatdayTotalAmount', number>) => number | string;
  }

  const statisticsData = ref<StatisticsItem[]>([
    {
      name: '当日总收入',
      flag: 'thatdayTotalAmount',
      format(val) {
        return formatNumberWithMoney(val?.thatdayTotalAmount || 0) ?? 0;
      },
    },
  ]);

  /**
   * 设置表格数据
   */
  async function getAxiosData(showLoading = true) {
    if (Array.isArray(dataRange.value) && dataRange.value.length) {
      filterData.value.startDate = dataRange.value[0];
      filterData.value.endDate = dataRange.value[1];
    } else {
      filterData.value.startDate = '';
      filterData.value.endDate = '';
    }
    try {
      await nextTick();
      getReferralCensusData(filterData.value).then((res) => {
        censusData.value.thatdayTotalAmount = res.data.thatdayTotalAmount;
      });
      baseData.loading = Boolean(showLoading);
      const res = await getMonitorLinkReportList(filterData.value);
      tableData.value = res.data.records;
      description.value = '暂无数据';
      filterData.value.current = res.data.current;
      filterData.value.size = res.data.size;
      baseData.total = res.data.total;
      baseData.loading = false;
    } catch (error) {
      baseData.loading = false;
      tableData.value = [];
      description.value = error.msg || '加载失败，-BD001';
    }
  }

  /**
   * 剧集详情
   */
  function dramaDetails(dramaId: string) {
    router.push(`/drama-management/drama-info?type=details&dramaId=${dramaId}`);
  }

  /**
   * 推广链接详情
   */
  async function referralLinkDetails(row: _MonitorLinkReportResponse) {
    try {
      row.getReferralLinkLoading = true;
      const res = await getReferralRecordListAxios({
        current: 1,
        size: 1,
        referralLinkId: `${row.referralLinkId!}`,
        referralLinkName: `${row.referralLinkName!}`,
      });
      if (res.data.records.length) {
        addPromotionLinkRef.value?.show({
          action: 'details',
          referralRecord: res.data.records[0]!,
        });
      }
      row.getReferralLinkLoading = false;
    } catch (error) {
      row.getReferralLinkLoading = false;
      ElToast.warning(error.msg || '加载失败，-BD001');
    }
  }

  /**
   * 获取回传记录
   */
  function handlerBackRecord(row: _MonitorLinkReportResponse) {
    backRecordRef.value?.show({ referralLinkId: row.referralLinkId!, thatdayDate: row.thatdayDate! });
    // router.push(`/marketing-management/link-return-record?referralLinkId=${row.referralLinkId!}`);
  }

  /**
   * 限制输入
   */
  function referralLinkIdLimit() {
    filterData.value.referralLinkId = verifyNumbInput('add_int_or_zero', filterData.value.referralLinkId, filterData.value.referralLinkId) as string;
  }

  /** 跳转每日消耗 */
  // function handleDayConsume(row: _MonitorLinkReportResponse) {
  //   router.push(`/marketing-management/juliang-daily-consumption?referralLinkId=${row.referralLinkId}`);
  // }

  /**
   * 手动同步
   */
  // async function handleManualUpdate(row: _MonitorLinkReportResponse) {
  //   try {
  //     row.manualUpdateLoading = true;
  //     await syncDataCensus({ referralCensusId: row.referralCensusId! });
  //     row.manualUpdateLoading = false;
  //     ElToast.success(`更新成功`);
  //     getAxiosData(false);
  //   } catch (error) {
  //     row.manualUpdateLoading = false;
  //     ElToast.error(error.msg || `更新失败，-BD004`);
  //   }
  // }
</script>

<style lang="scss" scoped>
  .pagination-box {
    @include flex(row, nowrap, center, center, center);
    padding-top: 15px;
  }

  .page-content {
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .head-box {
    @include flex(row, nowrap, flex-start, center, center);

    .left-box {
      // display: grid;
      display: flex;
      flex: 1;
      flex-wrap: wrap;
      // grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      // grid-gap: 15px;
      gap: 14px;
      margin-right: 15px;
    }
  }

  .content-wrap {
    white-space: wrap;
  }
</style>
